<?php

namespace App\Jobs;

use App\Models\FormIds;
use App\Models\TemplatesLog;
use App\Models\Tmplmsgs;
use App\Models\TmplmsgsLog;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class MessageForJobs implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    protected $arr;//分组后的小数组，每组1000个
    protected $templateInfo;//模板消息信息
    protected $update;//是否需要更新TemplatesLog记录

    public function __construct($arr,$templateInfo,$update)
    {
        $this->arr = $arr;
        $this->templateInfo = $templateInfo;
        $this->update = $update;
    }

    public function handle()
    {

        foreach ($this->arr as $key=>$item){
            if($this->update){
                //把查询的结果按当天日期存表，用于失败了不重复推送
                TemplatesLog::create([
                    'openid'=>$item['openid'],
                    'template_id'=>$this->templateInfo['template_id'],
                    'created_at'=>Carbon::now()->toDateString()
                ]);
            }
            //直接生成推送队列
            dispatch((new PushJobs($item['openid'],$this->templateInfo))->onQueue('daduizhang_push'));
        }
    }

    public function failed(\Exception $e)
    {
        Log::error($e->getMessage());
    }



}
